package com.wondertek.mist.database;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;

import com.wondertek.mist.po.NotiPo;

public class DataHelper {

	private SQLiteDatabase db;
	private SQLiteHelper sqLiteHelper;
	private static final byte[] _writeLock = new byte[0];

	public DataHelper(Context context) {
		sqLiteHelper = new SQLiteHelper(context, "mist", null,1);
		db = sqLiteHelper.getReadableDatabase();
	}

	public void close() {
		db.close();
		sqLiteHelper.close();
	}

	public void deleteAlltables() {

		sqLiteHelper.onUpgrade(db, 0, 0);
	}

	public void setWrite() {
		db = sqLiteHelper.getWritableDatabase();
	}



	
	public List<NotiPo> getAllNotis() {
		db = sqLiteHelper.getWritableDatabase();
		List<NotiPo> notiPos = new ArrayList<NotiPo>();
		Cursor cursor = db.query("noti", null, null, null, null,null, null);
		cursor.moveToFirst();
		while (!cursor.isAfterLast() && (cursor.getString(1) != null)) {
			NotiPo notiPo = new NotiPo();
			notiPo.setTitle(cursor.getString(0));
			notiPo.setContent(cursor.getString(1));
			notiPo.setExtra(cursor.getString(2));
			
			notiPos.add(notiPo);
			cursor.moveToNext();
		}
		cursor.close();
		return notiPos;
	}

	
	public Long saveNoti(NotiPo notiPo) {
		synchronized (_writeLock) {
			db = sqLiteHelper.getWritableDatabase();
			ContentValues values = new ContentValues();
			values.put("title", notiPo.getTitle());
			values.put("content", notiPo.getContent());
			values.put("extra", notiPo.getExtra());
			
			Long uid = db.insert("noti", null, values);
			return uid;
		}
	}


	public int delNoti() {
		synchronized (_writeLock) {
			db = sqLiteHelper.getWritableDatabase();
			int id = db.delete("noti", null, null);
			return id;
		}
	}

    class SQLiteHelper extends SQLiteOpenHelper {

		public SQLiteHelper(Context context, String name, CursorFactory factory, int version) {
			super(context, name, factory, version);

		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL("create table if not exists noti ( title varchar , content varchar , extra varchar )");

		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			this.onCreate(db);
		}

	}

	
}